<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2024/11/22 0022
 * Time: 15:01
 */

namespace app\admin\controller;

use app\admin\model\Borrow as BorrowModel;

class Borrow extends Base
{
    private $model;
    public function initialize()
    {
        parent::initialize();
        $this->model = new \app\admin\model\Borrow();
    }

    public function index()
    {
        return $this->fetch();
    }

    public function lst()
    {
        $start = $this->request->get('start', 0);
        $length  = $this->request->get('length', 15);
        $search  = $this->request->get('keyword');
        $where = [];
        if ($search) {
            $where[] = ['b.bname', 'like', "%{$search}%"];
        }
        $data = $this->model->getList($start, $length, $where);
        $total = $this->model->getListCount($where);
        $result = [
            'draw' => $this->request->get('draw'),
            'recordsTotal' => $total,
            'recordsFiltered' => $total,
            'data' => $data
        ];
        foreach ($data as $k => $v) {
            if ($v['status'] != 2){
                if ($v['back'] < date('Y-m-d')) {
                    $data[$k]['status'] = 1;
                }
            }
        }
        return json($result);
    }

    /**
     * Note: 编辑借阅
     * User: Mr.Yang
     * @return mixed
     */
    public function edit()
    {
        if ($this->request->isAjax()) {
            $data = $this->request->post('data/a', []);
            $id = $this->request->post('id', 0);
            $date = date('Y-m-d');
            $result = $this->validate($data, [
                'bookid' => 'require',
                'userid' => 'require',
                'back' => 'require|after:'.$date,
            ], [
                'bookid.require' => '图书必须',
                'userid.require' => '借阅人必须',
                'back.require' => '归还时间必须',
                'back.after' => '归还日期要大于'.$date,
            ]);
            if ($result !== true) {
                $this->error($result);
            }
            $borrow = BorrowModel::where('id', '=', $id)->findOrFail();
            if ($borrow['status'] == 2) {
                $this->error('该图书已归还');
            }
            $res = $this->model->edit($id, $data);
            if ($res !== false) {
                $this->success('编辑成功');
            }
            $this->error('编辑失败');
        }
        $id = $this->request->get('id');
        $borrow = $this->model->getOneById($id);
        $this->assign('borrow', $borrow);
        return $this->fetch();
    }

    public function del()
    {
        if ($this->request->isAjax()) {
            $id = $this->request->get('id');
            $res = $this->model->del($id);
            if ($res !== false) {
                $this->success('删除成功');
            }
            $this->error('删除失败');
        }
    }
}